<?php

namespace Api\Controller;

use Common\Controller\ApiController;

class CheckController extends ApiController {

    function _initialize() {
        parent::_initialize();
        //验证 APP KEY
        $timestamp = I('request.timestamp');
        $token = I('request.token');
        parent::checkAppToken($token, $timestamp);
    }

    //完善订购信息
    public function index($session3rd, $sel_address_id = 0) {
        $member_id = session($session3rd);
        if (!empty($member_id)) {
            $data['code'] = '200';
            $data['msg'] = '';

            //获取默认收货地址
            $MemberAddress = new \Home\Model\MemberAddressModel();
            if ($sel_address_id == 0) {
                $result['address'] = $MemberAddress->get_default_address($member_id);
            } else {
                $result['address'] = $MemberAddress->get_address($member_id, $sel_address_id);
            }

            //获取配送方式
            $ConfigDeliveryObj = new \Home\Model\ConfigDeliveryModel();
            $delivery = $ConfigDeliveryObj->get_list();
            $result['delivery'] = $delivery;

            //会员余额
            $MemberObj = new \Home\Model\MemberModel();
            $result['member_money'] = $MemberObj->get_money($member_id);
            //会员积分
            $result['member_point'] = $MemberObj->get_point($member_id);

            $data['data'] = $result;
        } else {
            $data['code'] = '300';
            $data['msg'] = session($session3rd) . '请先登录' . $session3rd;
        }
        $this->response($data, C('API_TYPE'));
    }

    //提交订单数据
    public function checkout($session3rd) {
        $data['code'] = '200';
        $data['msg'] = '';
        $MemberObj = new \Home\Model\MemberModel();
        $member_id = session($session3rd);
        if (!empty($member_id)) {

            $sel_address_id = I('post.sel_address_id', 0);
            $sel_delivery_id = I('post.sel_delivery_id', 0);
            $delivery_time = I('post.delivery_time', '');
            $pay_type = I('post.pay_type', '1');
            $total_pay_money = I('post.total_pay_money', 0);
            $total_point = I('post.total_point', 0);
            $remark_member = I('post.remark_member', '');
            $str_cart_list = I('post.cart_list', "");


            if ($sel_address_id == 0) {
                $data['code'] = '500';
                $data['msg'] = "请选择或者填写收货地址！";
            } elseif ($sel_delivery_id == 0) {
                $data['code'] = '500';
                $data['msg'] = "请选择配送方式！";
            } elseif ($delivery_time == "") {
                $data['code'] = '500';
                $data['msg'] = "请选择配送时间！";
            }
            if ($data['code'] == '500') {
                $this->response($data, C('API_TYPE'));
            }

            //购物车商品信息
            $CartObj = new \Home\Model\CartModel();

            if ($str_cart_list == "") {
                $data['code'] = '500';
                $data['msg'] = "选购商品不能为空！";
                $this->response($data, C('API_TYPE'));
            }

            $total_weight = 0;
            $cart_list = $CartObj->get_cart_app($str_cart_list);


            $myfile = fopen("order_log.txt", "w") or die("Unable to open file!");
            fwrite($myfile, $str_cart_list);
            fclose($myfile);
            foreach ($cart_list as $k => $v) {
                $cart_list[$k]['total'] = tofixed($v['price'] * $v['num'], 2);
                $total_weight += $v['weight'];
            }


            //获得收获地址
            $MemberAddress = new \Home\Model\MemberAddressModel();
            $address = $MemberAddress->get_address($member_id, $sel_address_id);
            if (empty($address)) {
                $data['code'] = '500';
                $data['msg'] = "请选择或者填写收货地址！";
                $this->response($data, C('API_TYPE'));
            }

            //配送方式
            $ConfigDeliveryObj = new \Home\Model\ConfigDeliveryModel();
            $delivery = $ConfigDeliveryObj->find($sel_delivery_id);
            if (empty($delivery)) {
                $data['code'] = '500';
                $data['msg'] = "请选择配送方式！";
                $this->response($data, C('API_TYPE'));
            }

            //积分抵扣
            $member_point = $MemberObj->get_point($member_id);
            if ($total_point > $member_point) {
                $data['code'] = '500';
                $data['msg'] = "你的积分不足！";
                $this->response($data, C('API_TYPE'));
            }
            $point_1_to_money = $this->config['point_1_to_money'];
            $point_pay_percent = $this->config['point_pay_percent'];
            $total_pay_point = $total_point * $point_1_to_money;
            if ($total_pay_point > $order['total'] * $point_pay_percent * 100) {
                $data['code'] = '500';
                $data['msg'] = "积分支付金额超过比例限制！";
                $this->response($data, C('API_TYPE'));
            }

            $MGoods = new \Home\Model\GoodsModel();
            if ($data['code'] == '200') {
                $order['time_create'] = time(); //下单时间
                $order['order_type'] = 0; //订单类型 0：普通订单
                $order['member_id'] = $member_id; //会员ID
                $OrderObj = new \Fwadmin\Model\OrderModel();
                $order['order_no'] = $OrderObj->get_order_no($order['order_type'], $order['member_id']); //订单编号
                $order['remark_member'] = $remark_member;
                //状态
                $order['status'] = 1; //订单状态： 1未审核 2已审核 3已完成 4已取消 5已作废
                $order['status_pay'] = 1; //支付状态： 1未支付 2部分支付 3已支付
                $order['status_delivery'] = 1; //配送状态：1未发货 2已发货 3已部分发货 4已收货
                $order['pay_type'] = $pay_type;

                //购物车总金额
                $total = 0;
                for ($i = 0; $i < count($cart_list); $i++) {
                    $item_id = $cart_list[$i]['item_id'];
                    $num = $cart_list[$i]['num'];
                    $price = $MGoods->get_item_price($item_id); //获取单件价格
                    $total += $num * $price;
                }
                $order['total_cart'] = $total;
                $order['total_weight'] = $total_weight; //总重量


                $order['addr_realname'] = $address['realname'];
                $order['addr_country'] = $address['country'];
                $order['addr_province'] = $address['province'];
                $order['addr_city'] = $address['city'];
                $order['addr_area'] = $address['area'];
                $order['addr_address'] = $address['address'];
                $order['addr_zip'] = $address['zip'];
                $order['addr_tel'] = $address['tel'];
                $order['addr_phone'] = $address['phone'];
                $order['addr_email'] = $address['email'];

                if ($delivery['type'] == 3) {//商品自提
                    $order['takeself'] = '';
                }
                $order['delivery_type'] = $delivery['delivery_name']; //配送方式
                $order['delivery_time'] = $delivery_time; //配送时间
                $total_delivery = $ConfigDeliveryObj->count_total_delivery($sel_delivery_id, $total_weight, $sel_address_id); //运费
                $order['total_delivery'] = $total_delivery;
                $order['total_save_price'] = 0;
                $order['total'] = $order['total_cart'] + $order['total_delivery'] + $order['total_save_price'];
                $order['total_discount'] = 0;
                $order['total_pay'] = 0;

                $order['total_point'] = $total_point;
                $order['total_pay_point'] = $total_pay_point;

                //是否保价
                $order['is_save_price'] = 0;
                $order['get_point'] = 0; //获得赠送积分
                //发票
                $order['is_invoice'] = 0; //是否需要发票：0不索要 1索要
                $order['invoice_title'] = ''; //发票抬头

                $order['source'] = 2; //'订单来源：Web APP'
                //保存订单操作
                $order_id = $OrderObj->data($order)->add();
                if ($order_id > 0) {
                    //添加订单商品表
                    foreach ($cart_list as $k => $v) {
                        $cart['order_id'] = $order_id;
                        $cart['order_no'] = $order['order_no'];
                        $cart['member_id'] = $order['member_id'];
                        $cart['goods_id'] = $v['goods_id'];
                        $cart['goods_sn'] = $v['goods_sn'];
                        $cart['goods_item_id'] = $v['item_id'];
                        $cart['goods_num'] = $v['num'];
                        $cart['goods_name'] = $v['goods_name'];
                        $cart['goods_price'] = $v['price'];
                        $cart['goods_picture'] = $v['picture'];
                        $cart['goods_weight'] = $v['weight'];
                        $cart['goods_spec'] = $v['spec_array'];
                        $cart['is_comment'] = 0;
                        $OrderGoodsObj = M('OrderGoods');
                        $cart_flag = $OrderGoodsObj->data($cart)->add();
                        if ($cart_flag <= 0) {
                            $SystemErrorObj = new \Fwadmin\Model\SystemErrorModel();
                            $SystemErrorObj->add_error('checkout', '订单商品添加失败', $OrderGoodsObj->_sql());
                        }
                    }
                    //添加订单记录
                    $OrderObj->add_order_record($order_id, '你提交了订单');
                    //余额支付金额
                    if ($total_pay_money > 0) {
                        $member_money = $MemberObj->get_money($member_id);
                        if ($member_money >= $total_pay_money) {
                            $MemberMoneyObj = new \Fwadmin\Model\MemberMoneyModel();
                            $MemberMoneyObj->add_record($member_id, -$total_pay_money, '余额支付', 0);
                            $OrderObj->pay_3($order_id, '余额支付', $total_pay_money);
                        }
                    }
                    //积分支付扣除会员金额
                    if ($total_point > 0) {
                        $MemberPointObj = new \Fwadmin\Model\MemberPointModel();
                        $MemberPointObj->add_record($member_id, -$total_point, '积分抵扣', 0);
                    }

                    //如果待支付金额为0 自动更新支付状态
                    $OrderObj->update_pay_status($order_id);

                    $data['order_id'] = $order_id;
                } else {
                    $data['code'] = '500';
                    $data['msg'] = "订单提交出错！";
                }
            }
        } else {
            $data['code'] = '300';
            $data['msg'] = session($session3rd) . '请先登录' . $session3rd;
        }
        $this->response($data, C('API_TYPE'));
    }

    /**
     * 订单提交成功页面
     * @param int $id 订单ID
     */
    public function success($id = 0) {
        $OrderObj = new \Fwadmin\Model\OrderModel();
        $order = $OrderObj->where(array('member_id' => $this->member_id, 'order_id' => $id))->find();
        if (empty($order)) {
            echo '非法操作！';
            exit();
        }
        $order['total_need_pay'] = $order['total'] - $order['total_discount'] - $order['total_pay'] - $order['total_pay_point'];
        $this->order = $order;

        //支付方式
        $PaymentObj = new \Home\Model\ConfigPaymentModel();
        $this->payment = $PaymentObj->get_list();

        //会员可用余额
        $MemberObj = new \Home\Model\MemberModel();
        $this->menber_money = $MemberObj->get_money($this->member_id);

        $this->display();
    }

    

    /**
     * 计算运费
     * @param type $delivery_id 配送方式ID
     * @param type $weight 重量（单位克）
     * @param type $address_id 地址ID
     */
    public function count_delivery($delivery_id, $weight, $address_id) {
        $ConfigDeliveryObj = new \Home\Model\ConfigDeliveryModel();
        $total_delivery = $ConfigDeliveryObj->count_total_delivery($delivery_id, $weight, $address_id);
        if ($total_delivery >= 0) {
            $data['status'] = 'success';
            $data['total_delivery'] = $total_delivery;
        } else {
            $data['status'] = $total_delivery;
            $data['total_delivery'] = -9999;
        }
        $this->ajaxReturn($data);
    }

    //获取会员收货地址
    public function get_address() {
        layout(false);
        //会员收货地址信息
        $MemberAddress = new \Home\Model\MemberAddressModel();
        $address = $MemberAddress->search($this->member_id);
        $address_list = $address['list'];
        $this->address_list = $address_list;
        $this->display();
    }
    
    /**
     * 订单提支付页面
     * @param int $id 订单ID
     */
    public function pay($id) {
        $OrderObj = new \Fwadmin\Model\OrderModel();
        $order = $OrderObj->where(array('member_id' => $this->member_id, 'order_id' => $id))->find();
        if (empty($order)) {
            echo '非法操作！';
            exit();
        }
        $order['total_need_pay'] = $order['total'] - $order['total_discount'] - $order['total_pay'] - $order['total_pay_point'];
        $this->order = $order;

        //支付方式
        $PaymentObj = new \Home\Model\ConfigPaymentModel();
        $this->payment = $PaymentObj->get_list();

        //会员可用余额
        $MemberObj = new \Home\Model\MemberModel();
        $this->menber_money = $MemberObj->get_money($this->member_id);

        $this->display();
    }

    /**
     * 余额支付
     * @param int $order_id 订单ID
     */
    public function pay_yue($order_id) {
        $OrderObj = new \Fwadmin\Model\OrderModel();
        $MemberObj = new \Home\Model\MemberModel();
        $order = $OrderObj->field('total,total_discount,total_pay,total_pay_point,status_pay')->where(array('member_id' => $this->member_id, 'order_id' => $order_id))->find();
        if (empty($order)) {
            echo '非法操作！';
            exit();
        }
        if ($order['status_pay'] == 3) {
            echo '你的订单已支付';
            exit();
        }
        $total_pay_money = $order['total'] - $order['total_discount'] - $order['total_pay'] - $order['total_pay_point']; //待支付金额
        $member_money = $MemberObj->get_money($this->member_id); //会员余额
        if ($member_money >= $total_pay_money) {
            $MemberMoneyObj = new \Fwadmin\Model\MemberMoneyModel();
            $flag = $MemberMoneyObj->add_record($this->member_id, -$total_pay_money, '余额支付', 0); //余额减少
            if ($flag > 0) {
                $OrderObj->pay_3($order_id, '余额支付', $total_pay_money); //更新订单状态
                echo 'success';
            }
        } else {
            echo '你的余额不足！请先充值';
        }
    }

}
